package com.epoch.wx.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.epoch.bussiness.wxuser.dao.WxUserDao;
import com.epoch.wx.util.WechatUtil;
import com.github.binarywang.wxpay.service.WxPayService;
import com.jfinal.core.Controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
/**
 *  小程序员基础基类
* <p>Title: ApiBaseController</p>  
* <p>Description: </p>  
* @author 544188838@qq.com
* @date 2018年9月2日
 */
public class ApiBaseController extends Controller{
	
	protected Logger logger = LoggerFactory.getLogger(ApiBaseController.class);
	
	public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";
		
	/**
	 * 微信小程序service
	 */
	protected WxMaService wxMaService = WechatUtil.getWxMaService();
	/**
	 * 微信支付service
	 */
	protected WxPayService wxPayService = WechatUtil.getWxPayService();
	
	/**
	 * 获取当前登录用户对象
	 * @return
	 */
	public WxUserDao getWxUser() {
		String userId = getAttrForStr(LOGIN_USER_KEY);
		if(null == userId) {
			userId = getPara(LOGIN_USER_KEY);
		}
		if(StringUtils.isNotBlank(userId)) {
			WxUserDao user = WxUserDao.dao.findById(userId);
			return user;
		}
		return null;
	}
	
	/**
	 * 获取请求数据
	 * @return
	 */
	public JSONObject getJsonRequest() {
        JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = getRequest().getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
	
	/**
	 * 微信请求：如果包含了application/json
	 * @return
	 */
	public JSONObject getJsonObject() {
		JSONObject result = new JSONObject();
		try {
			result = JSONObject.parseObject(getRawData());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 微信请求：如果包含了application/json
	 * 封装获取对象，
	 */
	public Map<String,Object> getPostData(){
		String rowData = getRawData();
		Map<String,Object> result = new HashMap<String,Object>();
		ObjectMapper mapper = new ObjectMapper();    
		 try {
			 result = mapper.readValue(rowData, Map.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
		return result;
	}
	
	/**
	 * 微信请求：如果包含了application/json，直接通过key获取字符串,就是这样获取
	 * @param key
	 * @return
	 */
	public String getJsonStrKey(String key) {
		String rowData = getRawData();
		try {
			JSONObject result = JSONObject.parseObject(rowData);
			return result.getString(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	  * 自定义响应数据
	 * @param requestCode
	 * @param msg
	 * @param data
	 * @return
	 */
	public Map<String, Object> toResponsObject(int requestCode, String msg, Object data) {
        Map<String, Object> obj = new HashMap<String, Object>();
        obj.put("errno", requestCode);
        obj.put("errmsg", msg);
        if (data != null)
            obj.put("data", data);
        return obj;
    }
	
	/**
	  * 响应数据，返回成功
	 * @param data
	 * @return
	 */
	public Map<String, Object> toResponsSuccess(Object data) {
        Map<String, Object> rp = toResponsObject(0, "执行成功", data);
        logger.info("response:" + rp);
        return rp;
    }
	
	/**
	  * 响应数据,前台直接在data里面取
	 * @param msg
	 * @return
	 */
	public Map<String, Object> toResponsMsgSuccess(String msg) {
        return toResponsObject(0, msg, "");
    }

	/**
	  * 响应数据,
	 * @param msg
	 * @return
	 */
    public Map<String, Object> toResponsSuccessForSelect(Object data) {
        Map<String, Object> result = new HashMap<>(2);
        result.put("list", data);
        return toResponsObject(0, "执行成功", result);
    }

    public Map<String, Object> toResponsFail(String msg) {
        return toResponsObject(1, msg, null);
    }
    
    /**
        * 获取请求IP，有时候微信请求会用到IP，这时候就拿这个
     * @return
     */
    public String getClientIp() {
        String xff = getRequest().getHeader("x-forwarded-for");
        if (xff == null) {
            return "8.8.8.8";
        }
        return xff;
    }
}
